package com.example.dell.fastshopping.mall;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.dell.fastshopping.DuoBao.DuoBaoActActivity;
import com.example.dell.fastshopping.R;
import com.example.dell.fastshopping.mall.entity.MallEntity;
import com.example.dell.fastshopping.mall.model.DuoBaoMallViewModel;
import com.example.dell.fastshopping.views.BaseListFragmnet;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class DuoBaoMallFragment extends BaseListFragmnet {

    @BindView(R.id.rv)
    RecyclerView mall_rv;
    @BindView(R.id.nodata)
    LinearLayout nodata;
    private DuoBaoMallViewModel mViewModel;
    private List<MallEntity.MallItem> data;

    private MyHandler myHander;
    @BindView(R.id.refresh)
    TwinklingRefreshLayout refresh;
    private Unbinder bind;
    private int status;
    private int id;

    private static class MyHandler extends Handler {

        private final WeakReference<DuoBaoMallFragment> activityWeak;

        public MyHandler(DuoBaoMallFragment fragment) {
            activityWeak = new WeakReference<>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (activityWeak.get() != null) {
                activityWeak.get().receiveMessage(msg);
            }
        }
    }

    private void receiveMessage(Message msg) {
        MallEntity.MallItem item = data.get(msg.arg1);
        if (item.getEndTime() > System.currentTimeMillis()) {
            mall_rv.getAdapter().notifyItemChanged(msg.arg1);
            Message obtain = Message.obtain();
            obtain.arg1 = msg.arg1;
            myHander.sendMessageDelayed(obtain, 1000);
        } else {
            item.setStatus(3);
            mall_rv.getAdapter().notifyItemChanged(msg.arg1);
        }
    }


    public static DuoBaoMallFragment newInstant(int status, int id) {
        DuoBaoMallFragment duoBaoMallFragment = new DuoBaoMallFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("status", status);
        bundle.putInt("id", id);
        duoBaoMallFragment.setArguments(bundle);
        return duoBaoMallFragment;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        bind.unbind();
        if (myHander != null) {
            myHander.removeCallbacksAndMessages(null);
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.duobao_mall_fragment, container, false);
        bind = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = ViewModelProviders.of(this).get(DuoBaoMallViewModel.class);
        initView();
    }

    @Override
    protected void getNetData(int pageNum, int pageSize) {
        getData(pageNum, pageSize);
    }

    @Override
    protected TwinklingRefreshLayout getRefreshLayout() {
        return refresh;
    }

    private void initView() {
        Bundle bundle = getArguments();
        status = bundle.getInt("status", 0);
        id = bundle.getInt("id", 0);
        myHander = new MyHandler(this);
        mall_rv.setLayoutManager(new LinearLayoutManager(mContex));
        mall_rv.setItemAnimator(null);
        mall_rv.addItemDecoration(new DividerItemDecoration(mContex, DividerItemDecoration.VERTICAL));

    }

    @Override
    public void onResume() {
        super.onResume();
        pageNum = 1;
        pageSize = 15;
        getData(1, 15);
    }

    private void getData(final int pageNum, int pageSize) {
        mViewModel.getItemList(id, pageNum, pageSize, status).observe(this, new Observer<MallEntity>() {
            @Override
            public void onChanged(@Nullable MallEntity mallItem) {
                if (pageNum == 1) {
                    data = mallItem.getList();
                } else {
                    data.addAll(mallItem.getList());
                }
                if (data.size() > 0) {
                    nodata.setVisibility(View.GONE);
                } else {
                    nodata.setVisibility(View.VISIBLE);
                }
                if (mall_rv.getAdapter() == null) {
                    mall_rv.setAdapter(new MyAdapter());
                } else {
                    mall_rv.getAdapter().notifyDataSetChanged();
                }
                loadFinsh();
                myHander.removeCallbacksAndMessages(null);
                for (int position = 0; position < data.size(); position++) {
                    MallEntity.MallItem mallItem1 = data.get(position);
                    if (mallItem1.getStatus() != 3) {
                        Message obtain = Message.obtain();
                        obtain.arg1 = position;
                        myHander.sendMessage(obtain);
                    }
                }
            }
        });
    }

    private void myStartActivity(int auctionClassId, int goodId) {
        Intent intent = new Intent(mContex, DuoBaoActActivity.class);
        intent.putExtra("auctionClassId", auctionClassId);
        intent.putExtra("goodId", goodId);
        startActivity(intent);
    }

    private class MyAdapter extends RecyclerView.Adapter<MyHolder> {

        @NonNull
        @Override
        public MyHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            View view = LayoutInflater.from(mContex).inflate(R.layout.item_duobao_mall, viewGroup, false);
            MyHolder myHolder = new MyHolder(view);
            return myHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull MyHolder viewHolder, int i) {
            MallEntity.MallItem mallItem = data.get(i);
            long startTime = mallItem.getStartTime();
            long endTime = mallItem.getEndTime();
            int status = mallItem.getStatus();

            if (status == 3) {
                //3 就不用循环了，时间判断在竞拍中 也可能是结束状态（流拍）
                viewHolder.status.setText("竞拍已结束");
                viewHolder.status_button.setBackgroundResource(R.drawable.gray_buttom);
                viewHolder.status_button.setTextColor(mContex.getResources().getColor(R.color.white));
                viewHolder.status_button.setText("已结束");
                viewHolder.status.setBackgroundResource(R.drawable.jinpai_status_gray);
            } else {
                if (startTime <= System.currentTimeMillis() && System.currentTimeMillis() <= endTime) {
                    viewHolder.status.setText("正在竞拍中");
                    viewHolder.status_button.setTextColor(mContex.getResources().getColor(R.color.white));
                    viewHolder.status_button.setBackgroundResource(R.drawable.red_button2);
                    viewHolder.status_button.setText("进行中");
                    long tiem = endTime - System.currentTimeMillis();
                    String[] timeArray = mViewModel.getTimeArray(tiem);
                    viewHolder.to_endtime.setText("距结束时间" + timeArray[0] + ":" + timeArray[1] + ":" + timeArray[2]);
                    viewHolder.status.setBackgroundResource(R.drawable.jingpai_stauts);
                } else if (System.currentTimeMillis() > endTime) {
                    viewHolder.status.setText("竞拍已结束");
                    viewHolder.status_button.setBackgroundResource(R.drawable.gray_buttom);
                    viewHolder.status_button.setTextColor(mContex.getResources().getColor(R.color.white));
                    viewHolder.status_button.setText("已结束");
                    viewHolder.status.setBackgroundResource(R.drawable.jinpai_status_gray);
                } else {
                    long tiem = startTime - System.currentTimeMillis();
                    String[] timeArray = mViewModel.getTimeArray(tiem);
                    viewHolder.status_button.setTextColor(mContex.getResources().getColor(R.color.myRed));
                    viewHolder.status_button.setBackgroundResource(R.drawable.red_empty_stoke_buttom);
                    viewHolder.status.setText("距开始" + timeArray[0] + ":" + timeArray[1] + ":" + timeArray[2]);
                    viewHolder.status_button.setText("即将开始");
                    viewHolder.status.setBackgroundResource(R.drawable.jingpai_stauts);
                }
            }
            viewHolder.setAuctionClassId(mallItem.getId());
            viewHolder.setGoodId(mallItem.getProductId());
            viewHolder.good_title.setText(mallItem.getTitle());
            viewHolder.start_price.setText("起拍价格" + mallItem.getStartPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            //  Glide.with(mContex).load(mallItem.getProductPic()).centerCrop().into(viewHolder.product_pic);

        }

        @Override
        public int getItemCount() {
            return data.size();
        }
    }

    private class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        private TextView status;
        private TextView to_endtime;
        private TextView status_button;
        private TextView good_title;
        private TextView start_price;
        private ImageView product_pic;
        private int auctionClassId;
        private int goodId;

        public MyHolder(View view) {
            super(view);
            status = view.findViewById(R.id.status);
            to_endtime = view.findViewById(R.id.to_endtime);
            status_button = view.findViewById(R.id.status_button);
            good_title = view.findViewById(R.id.good_title);
            start_price = view.findViewById(R.id.start_price);
            product_pic = view.findViewById(R.id.product_pic);
            view.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            myStartActivity(auctionClassId, goodId);
        }

        public void setAuctionClassId(int id) {
            this.auctionClassId = id;
        }

        public void setGoodId(int id) {
            this.goodId = id;
        }
    }
}
